package com.study.spmongodb.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author MI
 * @version 1.0
 * @date 2020/10/19 12:01
 */
public class ReentrantLockTest2 {
    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(ReentrantLockTest2::testLockInterrupt);

        thread1.start();
        TimeUnit.SECONDS.sleep(1);

        Thread thread2 = new Thread(ReentrantLockTest2::testLockInterrupt);
        thread2.start();
        TimeUnit.SECONDS.sleep(1);

        thread2.interrupt();
    }

    public static void testLockInterrupt() {
        try {
            // 可以被打断
            lock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName() + "开始工作");
            while (true) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * lock方法是不可被打断的，即调用线程的interrupt方法不起作用
     *
     * @throws InterruptedException
     */
    private static void interrupt() throws InterruptedException {
        Thread thread1 = new Thread(ReentrantLockTest2::testLockUnInterruptibly);
        thread1.start();
        TimeUnit.SECONDS.sleep(1);

        Thread thread2 = new Thread(ReentrantLockTest2::testLockUnInterruptibly);
        thread2.start();
        TimeUnit.SECONDS.sleep(1);

        //lock方法是不可被打断的，即调用线程的interrupt方法不起作用
        thread2.interrupt();
    }

    public static void testLockUnInterruptibly() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "开始工作");
            while (true) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
